package com.example.player.presentation.adaptor;

import android.animation.ValueAnimator;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.example.player.R;
import com.example.player.domain.entity.Song;
import com.example.player.presentation.fragment.ItemExtend;
import com.example.player.util.MediaPlayerHelper;

import java.io.File;
import java.util.List;

import io.reactivex.rxjava3.disposables.CompositeDisposable;

/**
 * 音乐条目适配器
 *
 * @author 朱文权
 */
public class SongItemAdapter extends RecyclerView.Adapter<SongItemAdapter.SongItemViewHolder> implements RecyclerViewAdapter<List<Song>> {
    /**
     * 歌曲列表
     */
    private List<Song> songList;
    /**
     * 当前选中的位置
     */
    private int selectedPosition = -1;
    /**
     * 上一个选中的位置
     * */
    private int preSelected=-1;
    private MediaPlayerHelper player=new MediaPlayerHelper();
    public SongItemAdapter(List<Song> songList) {
        this.songList = songList;
    }

    /**
     * 用于数据库数据更新时更新ui
     */
    public void setData(List<Song> songList) {
        this.songList = songList;
        //设置未选中态
        for (Song song : songList) {
            song.setSelected(-1);
        }
        this.selectedPosition = -1;
        //进行简单的数据更新
        notifyDataSetChanged();
    }

    /**
     * 全局点击事件处理
     */
    private void onItemClick(int position) {
        int prevSelected = selectedPosition;
        selectedPosition = position;
        Song song=songList.get(position);
        //判断点击的音乐是处于什么状态
        int status=song.getPlayStatus();
        if(status==2){
            player.pause(song);
        }else {
            player.play(song);
        }
        // 更新前一个选中项的状态
        if (prevSelected != -1) {
            songList.get(prevSelected).setSelected(-1);
            notifyItemChanged(prevSelected);
        }
        // 更新当前选中项的状态
        songList.get(selectedPosition).setSelected(1);
        notifyItemChanged(selectedPosition);
    }

    /**
     * 将布局与holder绑定
     */
    @NonNull
    @Override
    public SongItemViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.song_item, parent, false);
        return new SongItemViewHolder(view);
    }

    /**
     * 将数据填充至组件中，并对组件进行某些操作
     */
    @Override
    public void onBindViewHolder(@NonNull SongItemViewHolder holder, int position) {
        Song song = songList.get(position);
        holder.bind(song);
    }

    /**
     * 共有多少条数据
     */
    @Override
    public int getItemCount() {
        return songList.size();
    }
    /**
     * 释放资源
     * */
    public void release(){
        player.release();
    }
    /**
     * 封装该视图下的组件
     */
    public class SongItemViewHolder extends RecyclerView.ViewHolder {
        /**
         * 异步操作订阅
         */
        private CompositeDisposable disposable = new CompositeDisposable();
        private ValueAnimator colorAnimator;
        private Song song;
        private ImageView imageView;
        private View itemView;
        private TextView title;
        private TextView artist;
        private ImageButton extend;
        public SongItemViewHolder(View view) {
            super(view);
            this.itemView = view;
            //绑定点击事件
            itemView.setOnClickListener(v -> {
                if (getAdapterPosition() != RecyclerView.NO_POSITION) {
                    SongItemAdapter.this.onItemClick(getAdapterPosition());
                }
            });
            title = view.findViewById(R.id.tv_title);
            artist = view.findViewById(R.id.tv_artist_duration);
            extend = view.findViewById(R.id.btn_extend);
            imageView = view.findViewById(R.id.iv_album_art);
            extend.setOnClickListener(v -> {
                onExtendClick();
            });
        }

        /**
         * 绑定数据
         */
        public void bind(Song song) {
            //释放上一次异步操作的订阅
            disposable.clear();
            this.song = song;
            title.setText(song.getTitle());
            artist.setText(song.getArtist() + " | " + song.getDuration());
            // 取消之前的动画（防止复用导致状态冲突）
            if (colorAnimator != null && colorAnimator.isRunning()) {
                colorAnimator.cancel();
            }
            // 根据选中状态启动颜色过渡动画
            if (song.getSelected() == 1) {
                startSelectionAnimation(itemView, ContextCompat.getColor(itemView.getContext(), R.color.white), ContextCompat.getColor(itemView.getContext(), R.color.selected));
            } else if (song.getSelected() == -1) {
                itemView.setBackgroundColor(ContextCompat.getColor(itemView.getContext(), R.color.white));
            }
            //加载图片
            if(song.getCoverPath()!=null){
                Glide.with(itemView.getContext())
                        .load(new File(song.getCoverPath()))
                        .placeholder(R.drawable.loading)  // 加载中的占位图
                        .error(R.drawable.song_cover)         // 加载失败时显示的图片
                        .into(imageView);
            }else {
                Glide.with(itemView.getContext())
                        .load(R.drawable.song_cover)
                        .into(imageView);
            }
        }

        /**
         * 颜色变化动画
         */
        private void startSelectionAnimation(View view, int startColor, int endColor) {
            colorAnimator = ValueAnimator.ofArgb(startColor, endColor);
            colorAnimator.setDuration(80);
            colorAnimator.addUpdateListener(anim -> {
                view.setBackgroundColor((int) anim.getAnimatedValue());
            });
            colorAnimator.start();
        }

        /**
         * extend点击事件处理
         */
        private void onExtendClick() {
            AppCompatActivity activity = (AppCompatActivity) itemView.getContext();
            new ItemExtend(extend,song).show(activity.getSupportFragmentManager(), "ItemExtend");
        }

    }
}
